package com.falser.user.controller;

import com.falser.common.dto.UserInfoDTO;
import com.falser.common.exception.BaseException;
import com.falser.common.web.ApiResponse;
import com.falser.user.dto.LoginSuccessDTO;
import com.falser.user.service.SysUserService;
import com.falser.user.vo.LoginVO;
import com.falser.user.vo.RegisterVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 * 身份验证控制器
 *
 * @author 10235
 * @date 2021/12/12
 */
@Api(tags = "认证")
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private final SysUserService sysUserService;

    public AuthController(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    @PostMapping("login")
    @ApiOperation("登录")
    public ApiResponse<LoginSuccessDTO> login(@Valid @RequestBody LoginVO vo) {
        return ApiResponse.ofSuccess(sysUserService.login(vo));
    }

    @GetMapping("userinfo")
    @ApiOperation("获取登录用户信息")
    public ApiResponse<UserInfoDTO> getUserInfo() {
        return ApiResponse.ofSuccess(sysUserService.getUserInfo());
    }

    @PostMapping("logout")
    @ApiOperation("登出")
    public ApiResponse<String> logout() {
        sysUserService.logout();
        return ApiResponse.ofSuccess();
    }


    @PostMapping("register")
    @ApiOperation("注册")
    public ApiResponse<String> register(@Valid @RequestBody RegisterVO vo) {
        if (!Objects.equals(vo.getPassword(), vo.getRePassword())) {
            throw new BaseException("两次密码不一致");
        }
        sysUserService.register(vo);
        return ApiResponse.ofSuccess();
    }
}
